package com.kr.weitao.util.spring;

import com.kr.weitao.exception.CommonException;
import org.springframework.context.ConfigurableApplicationContext;

/** Created by paco on 2017/06/08. */
//@Log4j2
public class SpringUtils {
  //定义appicationContext对象
  private static ConfigurableApplicationContext ctx = null;

  public static void setApplicationContext(ConfigurableApplicationContext ccts) {
    //log.debug(SpringUtils.class.toString() + ":init ConfigurableApplicationContext");
    SpringUtils.ctx = ccts;
    ctx.registerShutdownHook();
  }

  private static void getCpac() {
    if (ctx == null) {
      throw new CommonException("-50", "上下文信息有误");
    }
  }

  public static <T> T getBean(Class<T> beanCls) {
    //log.debug(SpringUtils.class.toString() + ":getBean<T>:" + beanCls.getName());
    getCpac();
    return ctx.getBean(beanCls);
  }

  private static ConfigurableApplicationContext getCtx() {
    //log.debug(SpringUtils.class.toString() + ":getCtx");
    getCpac();
    return ctx;
  }

  public static <T> T getBean(String beanName) {
    //log.debug(SpringUtils.class.toString() + ":getBean：" + beanName);
    getCpac();
    return (T) ctx.getBean(beanName);
  }

  public static synchronized void shutdown() {
    if (ctx != null) {
      ctx.close();
      ctx = null;
    }
  }
}
